#include "texture.h"
#include "texture/textureloader.h"
#include "render/renderer.h"
#include "core/Platform.h"

using namespace kraw;

Texture::Texture(AssetLoader* loader) :
Resource(loader)
{
	textureWidth = 0;
	textureHeight = 0;

	//OGLES2-specific
	textureID = 0;
	textureFilterMode = GL_LINEAR;
	textureClampMode = GL_CLAMP_TO_EDGE;
}

bool Texture::doLoad()
{
	//initialize actual texture from the source data
	TextureLoader* textureLoader = static_cast<TextureLoader*>(loader);

	//OGLES2-specific
	if (textureID != 0)
        glDeleteTextures(1, &textureID);
    
    glGenTextures(1, &textureID);
	glBindTexture(GL_TEXTURE_2D, textureID);

    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, textureFilterMode);
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, textureFilterMode);

    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, textureClampMode);
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, textureClampMode);

    switch (pixelFormat)
	{	
		case PixelFormat_RGBA8888:
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureLoader->pixels);
			memorySize = textureWidth * textureHeight * 4;
            break;
		case PixelFormat_RGB565:
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureWidth, textureHeight, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureLoader->pixels);
            memorySize = textureWidth * textureHeight * 2;
            break;
        case PixelFormat_A8:
			glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, textureWidth, textureHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, textureLoader->pixels);
            memorySize = textureWidth * textureHeight;
            break;
        default:
			//LOGE("Error loading image data %s: Invalid pixel format", textureLoader->resourceName);
            return false;
    }

	return true;
}
